<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace yiike\user\controllers;

use Yii;
use yiike\user\models\Token;
use common\models\User;
use common\helpers\CommonHelper;

/**
 * Description of RegisterController
 *
 * @author Administrator
 */
class RegisterController extends \api\components\Controller {

    public function behaviors() {
        return [
            'verbs' => [
                'class'   => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'index' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex() {

        $mobile    = Yii::$app->request->post('mobile');
        $name      = Yii::$app->request->post('name');
        $password  = Yii::$app->request->post('password');
        $smscode   = Yii::$app->request->post('smscode');
        
        /*
         * 检查手机验证码
         */
        $validator = new \common\models\SmsValidator();
        list($ret, $msg) = $validator->validateCode($mobile, 'register', $smscode);
        if ($ret !== TRUE) {
            return ['code' => $ret, 'message' => $msg];
        }

        $registerForm = new \yiike\user\models\RegistrationForm();
        $registerForm->setAttributes([
            'username' => $mobile,
            'password' => $password
        ]);
        if ($registerForm->register()) {

            $user    = User::findOne(['username' => $mobile]);
            $profile = $user->profile;
            $profile->name = $name;
            $profile->update();
            
            $token   = Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_LOGIN]);
            $token->link('user', $user);

            return ['code' => 0, 'message' => '注册成功', 'username' => $mobile, 'name' => $profile->name, 'avatar' => $profile->avatar, 'token' => $token->code];
        }
        else {
            return ['code' => 100028, 'message' => CommonHelper::arrayToString($registerForm->errors)];
        }
    }


}
